import time
import os
import requests
import random
import uuid
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

webdriver_path = os.path.join("util", "msedgedriver.exe")

driver = webdriver.Edge(service=Service(webdriver_path))

# 最大化浏览器窗口
driver.maximize_window()

next_page_url = "https://www.vilipix.com/tags/%E5%8E%9F%E7%A5%9E/illusts?p=6"

# 计数，别爬太多
count = 0

while next_page_url and count < 1:
    driver.get(next_page_url)

    # 滚动到页面底部
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")

    # 等待页面加载
    time.sleep(3)

    # 通过动态加载的方式获取图片
    elements = driver.find_elements(By.XPATH, '//div[@class="el-image"]/img')

    # 获取图片的src属性
    result = [element.get_attribute("src") for element in elements]

    # 创建路径
    dir_path = os.path.join("resources", "vilipix_data", "明日方舟")
    os.makedirs(dir_path, exist_ok=True)

    for i, url in enumerate(result):
        response = requests.get(url)

        # 使用uuid生成唯一的文件名
        file_name = f"{uuid.uuid4()}.jpg"
        file_path = os.path.join(dir_path, file_name)

        with open(file_path, "wb") as f:
            f.write(response.content)

    #        time.sleep(random.uniform(1, 2))

    # 找到按钮元素
    try:
        button = driver.find_element(By.XPATH, '//button[@class="btn-next"]')
        button.click()
        time.sleep(3)
        next_page_url = driver.current_url
    except NoSuchElementException:
        next_page_url = None

    count += 1

driver.quit()
